import React, { useState, useRef, useEffect } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './RecommendItem.scss'
import { useAudio } from './AudioContext'

interface RecommendItemProps {
  title: string
  author?: string
  authorTitle?: string
  preview?: string
  wordCount?: number
  readCount?: number
  audioUrl?: string
}

const RecommendItem: React.FC<RecommendItemProps> = ({
  title,
  author = '',
  authorTitle = '',
  preview = '',
  wordCount = 0,
  readCount = 0,
  audioUrl = 'https://storage.googleapis.com/media-session/sintel/snow-fight.mp3' // 默认音频URL，实际使用时应替换为真实URL
}) => {
  // 生成唯一ID用于标识当前组件
  const itemId = useRef(`item-${Math.random().toString(36).substr(2, 9)}`).current
  const [currentText, setCurrentText] = useState('')
  const [progress, setProgress] = useState(0)
  const audioContext = useRef<Taro.InnerAudioContext | null>(null)
  
  // 使用全局音频上下文
  const { play, pause, isPlaying } = useAudio()
  const playing = isPlaying(itemId)
  
  // 初始化音频上下文
  useEffect(() => {
    // 监听全局音频播放状态
    if (!playing) {
      setProgress(0)
      setCurrentText('')
      return
    }
    
    // 创建本地音频上下文用于获取进度和时间信息
    audioContext.current = Taro.createInnerAudioContext()
    audioContext.current.src = audioUrl
    audioContext.current.onTimeUpdate(() => {
      if (audioContext.current) {
        const currentTime = audioContext.current.currentTime
        const duration = audioContext.current.duration
        setProgress(currentTime / duration * 100)
        
        // 模拟文字同步显示（实际应用中可能需要更复杂的时间戳对应关系）
        const previewText = preview || ''
        const textLength = previewText.length
        const textPosition = Math.floor((currentTime / duration) * textLength)
        setCurrentText(previewText.substring(0, textPosition))
      }
    })
    
    // 播放音频
    audioContext.current.play()
    
    return () => {
      if (audioContext.current) {
        audioContext.current.destroy()
      }
    }
  }, [playing, audioUrl, preview])
  
  // 播放/暂停控制
  const togglePlay = () => {
    if (playing) {
      pause()
    } else {
      play(itemId, audioUrl)
    }
  }
  return (
    <View className='recommend-item'>
      <View className='item-content'>
        {(author || authorTitle) && (
          <View className='author-info'>
            <Text className='author'>{author}</Text>
            {authorTitle && <Text className='author-title'>{authorTitle}</Text>}
          </View>
        )}
        
        {preview && (
          <View className='preview-content'>
            <Text className='preview'>
              {playing && currentText ? (
                <>
                  <Text className='highlighted-text'>{currentText}</Text>
                  <Text className='normal-text'>{preview.substring(currentText.length)}</Text>
                </>
              ) : (
                preview
              )}
            </Text>
          </View>
        )}
        
        {/* 音频播放控制 */}
        <View className='audio-controls'>
          <View className='play-button' onClick={togglePlay}>
            {playing ? '暂停' : '播放'}
          </View>
          {playing && (
            <View className='progress-bar'>
              <View className='progress-inner' style={{ width: `${progress}%` }}></View>
            </View>
          )}
        </View>
        
        <View className='item-footer'>
          {wordCount > 0 && <Text className='word-count'>{wordCount}个字</Text>}
          {readCount > 0 && <Text className='read-count'>{readCount}人读过</Text>}
        </View>
      </View>
    </View>
  )
}

export default RecommendItem